import { getFormIndex, nmAppErrorLog } from '@app-nextmesh/common/utils';
import { CommandDialog2 } from '@app-nextmesh/components/Dialogs';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import {
  ICollection,
  ModelEventType,
  ModelPickSwitchEvent,
  ModelPickTypesEvent,
  NMCollectionCmdDialogParams,
} from '@app-nextmesh/types';
import { events } from '@app-nextmesh/utils';
import { UiSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';

export default function BaseCollectionDialog({
  title,
  onClose,
  initFormData,
  params,
  pickTypes,
  collectionType,
  schema,
}: NMCollectionCmdDialogParams<{
  id: string;
  formData: ICollection;
}>) {
  const { projectInfo, setProjectInfo } = useProjectStore((state) => state);
  const [formDataIndex, setFormDataIndex] = useState<number>(undefined);
  const [formData, setFormData] = useState<ICollection>(null);

  // 暂时不显/隐Geometry，通过控制Geometry 的 polygon 来解决 闪烁（斑马纹）
  // useEffect(() => {
  //   if (documentManager.getMeshesData()?.length !== 0) {
  //     updateGeometriesVisible('show');
  //   }
  //   return () => {
  //     if (documentManager.getMeshesData()?.length !== 0) {
  //       updateGeometriesVisible('hide');
  //     }
  //   };
  // }, []);

  useEffect(() => {
    // 设置当前支持的拾取类型
    events.emit(ModelEventType.PickTypes, {
      types: pickTypes,
      mix: true, // 支持混合拾取选择
    } as ModelPickTypesEvent);
    if (params) {
      // 从id中解析出index
      setFormDataIndex(getFormIndex(params.id));

      setFormData(params.formData);

      const type = params.formData.EntityType;
      if (type) {
        // 设置当前拾取类型
        events.emit(ModelEventType.SetCurrentPickType, {
          type,
          clear: true,
        } as ModelPickSwitchEvent);
      }
    } else {
      // 新建时，进行初始化，自动命名
      let name: string = collectionType;
      let count = 0;
      const collections = projectInfo?.collections;
      if (collections) {
        count = collections?.length ?? 0;
      }
      name = `${name}${count + 1}`;
      // 自动生成一个名称
      setFormData({
        Name: name,
        Type: collectionType,
        ...initFormData,
      });
    }
  }, [projectInfo, params]);
  const uiSchema: UiSchema = {
    SelectedEntities: {
      'ui:field': 'entity',
      pickTypes: pickTypes,
    },
  };
  const onSubmit = async (data) => {
    if (!data) {
      return;
    }
    let collections = projectInfo.collections;
    if (!collections || !Array.isArray(collections)) {
      collections = [];
    }

    if (formDataIndex !== undefined) {
      collections[formDataIndex] = data;
    } else {
      collections.push(data);
    }
    projectInfo.collections = collections;
    try {
      await documentV2.updateCollections(projectInfo.collections);
      setProjectInfo({ ...projectInfo });
      onClose();
    } catch (error) {
      nmAppErrorLog('CmdCollection', 'onSubmit', error);
    }
  };
  return (
    <CommandDialog2
      title={title}
      onClose={onClose}
      formData={formData}
      schema={schema}
      extraUiSchema={uiSchema}
      onSubmit={onSubmit}
      showErrorList={false}
    />
  );
}
